package com.helper.debugger.utils.httpserver;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LocalHttpServer {
    public interface StartedCallback {
        void started(boolean success);
    }

    public static final int PORT = 9999;
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    private static ServerSocket serverSocket;
    private static ExecutorService executor = Executors.newSingleThreadExecutor();
    private static boolean isRunning = false;

    //强烈建议使用前台服务 LocalHttpServerService.start(context)来启动，避免被系统回收
    public static void start(StartedCallback callback) {
        if (isRunning) return;
        // 如果线程池已终止，重新创建
        if (executor == null || executor.isShutdown() || executor.isTerminated()) {
            executor = Executors.newSingleThreadExecutor(); // 或者 newCachedThreadPool()
        }
        executor.execute(() -> {
            try {
                serverSocket = new ServerSocket(PORT);
                isRunning = true;
                log("本地Http服务启动成功，监听端口: " + PORT);
                mainHandler.post(() -> {
                    if (callback != null) callback.started(true);
                });
                while (isRunning) {
                    Socket client = serverSocket.accept();
                    handleRequest(client);
                }
            } catch (IOException e) {
                mainHandler.post(() -> {
                    if (callback != null) callback.started(false);
                });
            }
        });
    }

    public static boolean isRunning() {
        return isRunning && serverSocket != null && !serverSocket.isClosed();
    }

    private static void handleRequest(Socket client) {
        new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                 OutputStream out = client.getOutputStream()) {

                // 解析请求头
                String requestLine = in.readLine();
                if (requestLine == null) return;

                // 构造响应
                String response = buildResponse(requestLine);
                out.write(response.getBytes(StandardCharsets.UTF_8));
                out.flush();

            } catch (IOException e) {
                error("请求处理失败：" + e);
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    error("客户端关闭错误：" + e);
                }
            }
        }).start();
    }

    private static String buildResponse(String requestLine) {
        // 解析请求方法
        String[] parts = requestLine.split(" ");
        String method = parts[0];
        String path = parts[1];

        // 添加 CORS 头
        StringBuilder headers = new StringBuilder()
                .append("HTTP/1.1 200 OK\r\n")
                .append("Content-Type: application/json\r\n")
                .append("Access-Control-Allow-Origin: *\r\n")
                .append("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n")
                .append("Connection: close\r\n\r\n");

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return headers.toString();
        }

        // 业务响应体
        String body = "canlog";
        return headers.append(body).toString();
    }

    public static void stop() {
        try {
            isRunning = false;
            if (serverSocket != null) {
                serverSocket.close();
                log("本地Http服务器已关闭");
            }
            executor.shutdownNow();
        } catch (IOException e) {
            error("本地Http服务器关闭失败：" + e);
        }
    }

    private static void log(String msg) {
        Log.i("[B]" + LocalHttpServer.class.getSimpleName(), msg);
    }

    private static void error(String msg) {
        Log.e("[B]" + LocalHttpServer.class.getSimpleName(), msg);
    }
}